package cn.cdzdjd.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.springframework.stereotype.Service;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.PipixVideoService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PipixVideoServiceImpl implements PipixVideoService {
	private String pipixUrl = "https://is.snssdk.com/bds/cell/detail/?cell_type=1&aid=1319&app_name=super&cell_id=";
	@Override
	public VideoInfoVO getVideoInfo(String locationUrl) {
		String[] uris = locationUrl.split("\\?");
		String[] paths = uris[0].split("/item/");
		String cell_id = paths[1];
		try {
			Response response = Jsoup.connect(pipixUrl +cell_id).ignoreContentType(true)
					.userAgent(BrowserConstant.USER_AGENT_PC).header("Accept", BrowserConstant.ACCEPT).execute();
			JSONObject json = new JSONObject(response.body());
			//System.out.println();
			JSONObject item = json.getJSONObject("data").getJSONObject("data").getJSONObject("item");
			String title = item.getString("content");
			//判断note节点是否未空，如果为null则说明是视频
			if(item.isNull("note")) {
				JSONObject video = item.getJSONObject("origin_video_download");
				JSONArray videoUrls =  video.getJSONArray("url_list");
				List<String> videoList = new ArrayList<>();
				for (int i = 0; i < videoUrls.length(); i++) {
					String videoUrl = videoUrls.getJSONObject(i).getString("url");
					videoList.add(UrlUtil.setHttps(videoUrl));
				}
				List<String> posterList = new ArrayList<>();
				String poster = video.getJSONObject("cover_image").getJSONArray("download_list").getJSONObject(0).getString("url");
				posterList.add(UrlUtil.setHttps(poster));
				return new VideoInfoVO(videoList, posterList, title, null);
			}else {
				JSONObject note = item.getJSONObject("note");
				JSONArray images = note.getJSONArray("multi_image");
				List<String> posterList = new ArrayList<>();
				for (int i = 0; i < images.length(); i++) {
					JSONObject image =  images.getJSONObject(i);
					JSONObject imagePath = image.getJSONArray("download_list").getJSONObject(0);
					String posterUrl = imagePath.getString("url");
					posterList.add(UrlUtil.setHttps(posterUrl));
				}
				return new VideoInfoVO(null, posterList, title, null);
			}
		} catch (IOException e) {
			log.error("jsoup访问异常");
			throw new RenException("访问异常");
		}
	}
}
